% Main script for running mobility & ER Analysis based on the
% exampleAnimalTable spreadsheet

% load ds ('data set') and ap ('analysis parameters')
[ds, ap] = getdsap;

% read metadata
Info_Table = readtable(fullfile(ds.metadataPath, ds.metadataFileName_forSecondaryAnalysis));

% Load structure that contains place cell information for all animals
load(fullfile(ds.metadataPath, 'Placeness_MetaData.mat'));

% define the structure
Mobility_and_ER_Data_Summary = [];

% start the clock after the prelude above
t_start = tic;
for ii = height(Info_Table):-1:1  
    META = table2struct(Info_Table(ii,:));
    animalName = Info_Table.animalName(ii);
    genotype = Info_Table.genotype(ii);
    drug = Info_Table.drug{ii};
    session1_dose = Info_Table.session1_dose(ii);
    session2_dose = Info_Table.session2_dose(ii);
    session1_context = Info_Table.session1_context(ii);
    session2_context = Info_Table.session2_context(ii);
    exptParadigm = Info_Table.exptParadigm(ii);
    % Have to be careful with which date to report 
    if strcmp(META.exptParadigm, '4h_memory_test')
        dateToFind = Info_Table.exptDate1{ii};
    elseif strcmp(META.exptParadigm, '24h_memory_test')
        dateToFind = string(strcat(Info_Table.exptDate1{ii}, {' '}, 'and', {' '}, Info_Table.exptDate2{ii}));
    end

    % try to load data
    try
        [Inscopix1, Inscopix2, Noldus1, Noldus2, Start_T1, Start_T2] = Load_RawData_For_Cellset_Pair(META, ds); 
        [PlaceCell_Summary1, PlaceCell_Summary2] = Find_Placeness_Summary_For_Cellset_Pair(META, Placeness_MetaData);
        isDataRead = true;
    catch
        isDataRead = false;
        formatSpec = "Retrieving imaging and tracking data for %s, %s failed";
        msg = compose(formatSpec, animalName{:}, dateToFind);
        warndlg(msg)
    end
    data = runMobilityandER_Analysis(Inscopix1, Inscopix2, Noldus1, Noldus2, Start_T1, Start_T2, PlaceCell_Summary1, PlaceCell_Summary2, dateToFind, animalName, drug, session1_dose, session2_dose, session1_context, session2_context, genotype, exptParadigm, ds, ap);
    Mobility_and_ER_Data_Summary = [Mobility_and_ER_Data_Summary, data];
end

% save workspace
save(fullfile(ds.metadataPath, 'Mobility and ER Data Summary.mat'), '-v7.3', 'Mobility_and_ER_Data_Summary')
% report
t_stop = toc(t_start);
disp("Mobility and ER analysis took " + string(t_stop) + " s")
% clear all variables
clear